package com.b2b.message.admin.shiro;

import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

import com.b2b.constant.ResultEnum;
import com.b2b.message.admin.bean.UserBean;
import com.b2b.utils.Tools;

/**
 * 版权：上海极和信息科技有限公司
 * 功能：shiro身份校验核心类
 * 作者：朱伟峰
 * 邮箱：zhuweifeng24@gmail.com
 * 日期：2017年6月6日
 */
public class ShiroRealm extends AuthorizingRealm
{
	@Autowired
	private StringRedisTemplate stringRedisTemplate;
	// 用户登录次数计数 redisKey 前缀
	private String SHIRO_LOGIN_COUNT = "shiro_login_count_";
	// 用户登录是否被锁定 一小时 redisKey 前缀
	private String SHIRO_IS_LOCK = "shiro_is_lock_";

	/**
	 * 认证信息(身份验证)
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException
	{
		UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
		String username = token.getUsername();
		String password = String.valueOf(token.getPassword());
		// 访问一次，计数一次
		ValueOperations<String, String> opsForValue = stringRedisTemplate.opsForValue();
		opsForValue.increment(SHIRO_LOGIN_COUNT + username, 1);
		// 计数大于5时，设置用户被锁定一小时
		if (Tools.genInt(opsForValue.get(SHIRO_LOGIN_COUNT + username)) >= 5)
		{
			opsForValue.set(SHIRO_IS_LOCK + username, "LOCK");
			stringRedisTemplate.expire(SHIRO_IS_LOCK + username, 1, TimeUnit.HOURS);
		}
		if ("LOCK".equals(opsForValue.get(SHIRO_IS_LOCK + username)))
		{
			throw new DisabledAccountException("帐号已锁定");
		}
		
		if (!username.equals("admin") || !password.equals("q1w2e3r4"))
		{
			throw new DisabledAccountException(ResultEnum.ERR_2006.getMessage());
		}
		// 登录成功 清空登录计数
		opsForValue.set(SHIRO_LOGIN_COUNT + username, "0");
		
		UserBean userBean = new UserBean();
		userBean.setAdminId(0l);
		userBean.setUserId(0l);
		userBean.setName("管理员");
		userBean.setMobile("18616260016");
		userBean.setIconUrl("");
		userBean.setNotes("消息系统管理员");
		userBean.setSex(0);
		
		return new SimpleAuthenticationInfo(userBean, password.toCharArray(), getName());
	}

	/**
	 * 授权
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals)
	{
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		UserBean userBean = (UserBean) principals.getPrimaryPrincipal();
		if (userBean == null)
			return info;
//		long adminId = userBean.getAdminId();
//		if (adminId <= 0)
//			return info;
//		EntityWrapper<AdminRole> adminRoleWrapper = new EntityWrapper<AdminRole>();
//		adminRoleWrapper.where("status=0").and("admin_id={0}", adminId);
//		List<AdminRole> adminRoleList = adminRoleService.selectList(adminRoleWrapper);
//		if (adminRoleList == null || adminRoleList.isEmpty())
//			return info;
//		
//		Long[] roleIds = new Long[adminRoleList.size()];
//		for (int i = 0; i < adminRoleList.size(); i++)
//			roleIds[i] = adminRoleList.get(i).getRoleId();
//		
//		EntityWrapper<Role> roleWrapper = new EntityWrapper<Role>();
//		roleWrapper.where("status=0").in("id", roleIds);
//		List<Role> roleList = roleService.selectList(roleWrapper);
//		if (roleList == null || roleList.isEmpty())
//			return info;
//		
//		// 添加角色sign
//		Set<String> roleSet = new HashSet<String>();
//		for (Role role : roleList)
//			roleSet.add(role.getSign());
//		info.setRoles(roleSet);
//		
//		EntityWrapper<RoleRight> roleRightWrapper = new EntityWrapper<RoleRight>();
//		roleRightWrapper.where("status=0").in("role_id", roleIds);
//		List<RoleRight> roleRightList = roleRightService.selectList(roleRightWrapper);
//		if (roleRightList == null || roleRightList.isEmpty())
//			return info;
//		
//		Long[] functionIds = new Long[roleRightList.size()];
//		for (int i = 0; i < roleRightList.size(); i++)
//			functionIds[i] = roleRightList.get(i).getFunctionId();
//		
//		EntityWrapper<Function> functionWrapper = new EntityWrapper<Function>();
//		functionWrapper.where("status=0").in("id", functionIds);
//		List<Function> functionList = functionService.selectList(functionWrapper);
//		if (functionList == null || functionList.isEmpty())
//			return info;
//		
		// 权限sing
//		Set<String> stringPermissions = new HashSet<String>();
//		for (Function function : functionList)
//			stringPermissions.add(function.getSign());
		
		Set<String> roleSet = new HashSet<String>();
		roleSet.add("*");
		info.setRoles(roleSet);
		Set<String> stringPermissions = new HashSet<String>();
		stringPermissions.add("*");
		info.setStringPermissions(stringPermissions);
		
		return info;
	}
	
}
